<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/29
 * Time: 11:14
 */
namespace App\Http\Controllers\Api\V5;

use App\Common\ApiData;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use App\Modules\EntBookInfo;
use App\Modules\EntBookImg;
use App\Modules\EntMemberInfo;
use App\Modules\EntBookSumUp;
use App\Modules\EntBookCollect;
use App\Modules\EntBookViewLog;
use Validator, DB;
use PHPMailer;
use App\Models\V5\BookModel;
use App\Models\V5\MemberModel;
use App\Repository\Comment;
use App\Models\V5\ScoreModel;



class BookController extends BaseController
{
    protected $url;
    private $apiData;
    use Comment;

    public function __construct(){
        $this->url      = env('ADMIN_HOST');
        $this->apiData  = new ApiData();
    }

    /**
     * 书籍分类
     *
     */
    public function getBookType()
    {
        $bookModel  = new BookModel();
        $bookTypes  = $bookModel->get_book_types();
        $data = ['message' => 'ok', 'code' => 200, 'booktypelist' => $bookTypes];
        return response()->json($data);
    }




    /**
     * 推荐书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookRecommendList()
    {
        $bookModel  = new BookModel();
        $recommentBooks = $bookModel->get_recomment_books();
        return response()->json(['message' => 'ok', 'code' => 200, 'bookrecommendlist' => $recommentBooks]);
    }




    /**
     * 添加读书改进计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookSumUpStore(Request $request)
    {
        $id     = $request->input('id');
        $upid   = $request->input('upid');
        $bookidea1 = $request->input('bookidea1');
        $bookidea2 = $request->input('bookidea2');
        $bookidea3 = $request->input('bookidea3');
        $bookidea4 = $request->input('bookidea4');


        $bookidea1 = emoji_text_encode($bookidea1);
        $bookidea2 = emoji_text_encode($bookidea2);
        $bookidea3 = emoji_text_encode($bookidea3);
        $bookidea4 = emoji_text_encode($bookidea4);


        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($request->input('tokenUserId'));

        if (!$memberInfo) {
            return response()->json(['message' => "用户不存在", 'code' => 3020]);
        }


        if($upid == 0){
            $sumpInfo = DB::table('booksumup')
                ->where('BookID',$id)
                ->where('MemNumber',$memberInfo->MemNumber)
                ->orderBy('SumUpID','DESC')
                ->first();
            if($sumpInfo){
                $upid = $sumpInfo->SumUpID;
            }
        }


        $dateTime   = date_time();
        if ($upid == 0) {   //验证是否已经添加过
            $entBookSumUp = new EntBookSumUp();
            $entBookSumUp->BookID = $id;
            $entBookSumUp->MemNumber = $memberInfo->MemNumber;
            $entBookSumUp->BookReview1 = $bookidea1;
            $entBookSumUp->BookReview2 = $bookidea2;
            $entBookSumUp->BookReview3 = $bookidea3;
            $entBookSumUp->BookReview4 = $bookidea4;
            $entBookSumUp->AddDate     = $dateTime;
            $entBookSumUp->save();

            //填写读书改进计划加 10 分
            //如果是在24点前填写改进计划，则加分
            $memberModel    = new MemberModel();
            $day            = date('w');
            $endTime        = strtotime(date('Y-m-d 23:59:59',time()));
            $integral       = 10;
            if($day == 3 && time() < $endTime) //周三的24点前
            {
                $integral += 10;
                $memberModel->add_member_integral($memberInfo->UserID,$integral,$id,"周三24点前完成读书改进计划");
            }
            else
            {
                $memberModel->add_member_integral($memberInfo->UserID,$integral,$id,"填写读书改进计划");
            }
        } else {    //验证是否已经添加过
            $entBookSumUp = EntBookSumUp::find($upid);
            $entBookSumUp->BookReview1 = $bookidea1;
            $entBookSumUp->BookReview2 = $bookidea2;
            $entBookSumUp->BookReview3 = $bookidea3;
            $entBookSumUp->BookReview4 = $bookidea4;
            $entBookSumUp->AddDate     = $dateTime;
            $entBookSumUp->save();
        }

        if ($entBookSumUp)
        {
            $sumpInfo   = EntBookSumUp::find($entBookSumUp->SumUpID);
            $sumpInfo->BookReview1  = emoji_text_decode($sumpInfo->BookReview1);
            $sumpInfo->BookReview2  = emoji_text_decode($sumpInfo->BookReview2);
            $sumpInfo->BookReview3  = emoji_text_decode($sumpInfo->BookReview3);
            $sumpInfo->BookReview4  = emoji_text_decode($sumpInfo->BookReview4);

            return apiData()->set_data('sumuplist',$sumpInfo)->send(200,'保存成功');
        }
        else
        {
            return apiData()->set_data('sumuplist',null)->send(3021,"保存失败");
        }
    }

    /**
     * 收藏书籍
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bookCollectStore(Request $request)
    {
        $result = 'no';
        $rules = [
            'mobile' => 'required',
            'id' => 'required',
            'key' => 'required',
            'timestamp' => 'required',
            'sign' => 'required'
        ];
        $messages = [
            'mobile.required' => 2031,
            'id.required' => 2032,
            'key.required' => 2033,
            'timestamp.required' => 2034,
            'sign.required' => 2035
        ];
        $mobile = $request->input('mobile');
        $key = $request->input('key');
        $id = $request->input('id');
        $timestamp = $request->input('timestamp');
        $sign = $request->input('sign');
        $params = ['mobile' => $mobile, 'key' => $key, 'id' => $id, 'timestamp' => $timestamp, 'sign' => $sign];
        $v = Validator::make($params, $rules, $messages);

        if ($v->fails())
        {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }
        else
        {
            $memNumber = $this->memNumber($mobile, $key);
            if (!$memNumber)
            {
                return response()->json(['message' => "用户不存在", 'code' => 3025]);
            }
        }



        $entBookInfo = EntBookInfo::where('BookID', $id)->where('DeleteMark', 1)->first();
        if ($entBookInfo) {
            $entBookCollect = EntBookCollect::select('ColID')
                ->where('MemNumber', $memNumber->MemNumber)
                ->where('BookID', $id)
                ->first();

            if (!$entBookCollect) {
                $BookCollectStore = new EntBookCollect();
                $BookCollectStore->BookID = $id;
                $BookCollectStore->MemNumber = $memNumber->MemNumber;
                $BookCollectStore->AddDate = date('Y-m-d H:i:s', time());
                $BookCollectStore->save();
                if ($BookCollectStore) {
                    return response()->json(['message' => 'ok', 'code' => 200]);
                } else {
                    return response()->json(['message' => $result, 'code' => 3022]);
                }
            } else {
                EntBookCollect::destroy($entBookCollect->ColID);
                return response()->json(['message' => 'ok', 'code' => 200]);
            }
        } else {
            return response()->json(['message' => $result, 'code' => 3024]);
        }

    }


    /**
     * 返回会员标示
     * @param string $mobile
     * @param string $appkey
     * @return mixed
     */
    protected function memNumber($mobile = '', $appkey = '')
    {
        $entBookInfo = EntMemberInfo::select('UserID','MemNumber', 'MemEndTime', 'States','YourName','email')
            ->where('DeleteMark', 1)
            ->where('AppKey', $appkey)
            ->where('UserName', $mobile)
            ->first();
        return $entBookInfo;
    }



    /**========Ron重新编码==========*/


    /**
     * 书籍详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function book_detail(Request $request)
    {
        //获取书籍详细
        $id             = $request->input('bookId',0);
        $userId         = $request->input('tokenUserId');


        $bookModel      = new BookModel();
        $bookInfo       = $bookModel->get_book_info($id);
        if($bookInfo == false)
        {
            return apiData()->send(4001,'书籍不存在');
        }
        //获得书籍的评论信息
        $commentNumber = DB::table('comments')
            ->where('lessons_id',$id)
            ->where('deleted_at')
            ->where('type',5)
            ->where('pid',0)
            ->count();

        $bookInfo->commentNumber    = $commentNumber;
        if($bookInfo->article)
        {
            $bookInfo->Description      = $bookInfo->article ;
        }
        else{
            $bookInfo->Description      = url("/home/book_inner?bookId=".$id);
        }

        $memberInfo = false;
        if($userId > 0)
        {
            $memberModel    = new MemberModel();
            $memberInfo     = $memberModel->get_member_info_by_id($userId);
        }

        //1.检查书籍是否免费书籍
        if($bookInfo->IsGratis == 0 &&  ($memberInfo == false || $memberInfo->isValid == false))
        {
            return apiData()->send(4002,'本书限登录会员');
        }

        //获取PPT
        $ppts           = $bookModel->get_book_ppt($id);
        $isCollect      = 0;
        $readPlan       = null;
        $email          = "";
        $bookInfo->selfScore    = 0;

        if($memberInfo)
        {
            $email  = $memberInfo->email;
            //判断是否收藏
            $bookCollect = EntBookCollect::select('ColID')
                ->where('MemNumber', $memberInfo->MemNumber)
                ->where('BookID', $id)
                ->get();
            $isCollect    = $bookCollect ? 1 : 0;

            //获取读书改进计划

            $memberNumber   = $memberInfo->MemNumber;
            $readPlan       = $bookModel->get_user_book_read_plan($id,$memberNumber);

            //自己的分数
            $selfScore = DB::table('score')
                ->where('user_id',$userId)
                ->where('content_id',$id)
                ->where('content_type','lhdd')->first();
            if($selfScore)
            {
                $bookInfo->selfScore    = $selfScore->score;
            }

        }

        //更新书籍查看数
        DB::table('BookInfo')->where('BookID', $id)->increment('ReadNumber');
        $bookInfo->isCollect = $isCollect;
        $pas = [
            'bookId'    => $id,
            'userId'    => $userId
        ];
        $pas    = http_build_query($pas);

        if($readPlan)
        {
            $shareInfo	 = [
                'title'			=> $memberInfo->YourName."读《".$bookInfo->BookTitle."》的改进计划",
                'description'	=> $readPlan->BookReview1,
                'img'			=> $bookInfo->book_img,
                'link'			=> env('ADMIN_HOST')."/home/share_read_plan?".$pas,
                'groupTitle'	=> $memberInfo->YourName."读《".$bookInfo->BookTitle."》的改进计划\n教导读书会"
            ];
        }
        else
        {
            $shareInfo	 = [
                'title'			=> $bookInfo->BookTitle,
                'description'	=> $bookInfo->BookDesc,
                'img'			=> $bookInfo->book_img,
                'link'			=> env('ADMIN_HOST')."/home/share_read_plan?".$pas,
                'groupTitle'	=> "《".$bookInfo->BookTitle."》——$bookInfo->BookDesc\n教导读书会"
            ];
        }

        //$ip     = \EasyWeChat\Payment\get_client_ip();
//
//        $ipInfo = get_ip_address($ip);
//        if($ipInfo && $ipInfo->country != '中国')
//        {
//            $bookInfo->mp4 = "http://media.world".substr($bookInfo->mp4,12);
//            $bookInfo->mp3 = "http://media.world".substr($bookInfo->mp3,12);
//        }

        return apiData()
            ->set_data('ppts',$ppts)
            ->set_data('bookdetail',$bookInfo)
            ->set_data('sumuplist',$readPlan)
            ->set_data('shareInfo',$shareInfo)
            ->set_data('email',$email)
            ->send(200,"ok");

    }



    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookList(Request $request)
    {

        //friendUserId 本参数在用户查看好友的读书情况时使用（且必填）
        $friendUserId   = $request->input('friendUserId',0);
        $keyWords       = $request->input('keywords');
        $userId         = $request->input('tokenUserId',0);
        $page           = $request->input('page',1);
        $key            = $request->input('appKey','');
        $bookType       = $request->input('bookTypeId',0);
        //读取所有书籍
        $bookModel      = new BookModel();
        $entBookInfo    = $bookModel->page_book_list('lhdd',2,$keyWords,$bookType);

        $lastBookInfo   = $bookModel->get_last_book_info();


        foreach ($entBookInfo as $book)
        {
            $book->hasReadPlan  = 0;
            $book->Description  = $book->article ? $book->article : url("/home/book_inner?bookId=".$book->BookID);
            $book->bg_img       = env('HOST')."/".$book->bg_img;
            $book->ReadNumber   = change_read_number($book->ReadNumber);
            $book->sub_title    = $lastBookInfo->BookID == $book->BookID ? 1 : 0;
        }


        $entMemberInfo  = false;
        $memberModel    = new MemberModel();
        if($userId)
        {
            $entMemberInfo = $memberModel->get_member_info_by_id($userId);
        }

        if($entMemberInfo)
        {
            $memTime    = $entMemberInfo->AddDate;
            $memNumber  = $entMemberInfo->MemNumber;


            //取出该会员所有收藏的书籍
            $collectedBook  = $bookModel->get_member_collected_book($memNumber);
            $colllist       = [];
            foreach($collectedBook as $book){
                array_push($colllist,$book->BookID);
            }


            $readPlanUserMember = $memNumber; //好友的读书改进  如果没有好友 则是自己
            if($friendUserId >0)
            {
                $friendInfo         = $memberModel->get_member_info_by_id($friendUserId);
                $readPlanUserMember = $friendInfo->MemNumber;
            }

            //取出已经填写过读书计划的书籍
            $hasWriteReadPlan = DB::table('booksumup')
                ->where('MemNumber',$readPlanUserMember)
                ->distinct()
                ->pluck('BookID')
                ->toArray();
            $hasWriteReadPlan = $hasWriteReadPlan?$hasWriteReadPlan:[];

            //程序调整书籍排列顺序0不显示 1显示
            foreach ($entBookInfo as $book) {
                $bookAddTime    = $book->AddDate;
                $memberAddTime  = $memTime;
                if (strtotime($bookAddTime) > strtotime($memberAddTime)) {
                    $book->IsShow = 0;
                }

                //是否收藏过该书籍 0-否 1-是--MasterID
                $bookId = $book->BookID;
                $book->MasterID     = in_array($bookId, $colllist)?1:0;
                $book->hasReadPlan  = in_array($bookId, $hasWriteReadPlan)?1:0;
            }

            $memStatus = get_user_status(true,$entMemberInfo->States,$entMemberInfo->MemEndTime,$key);
        }else{
            $memStatus = get_user_status(false);
        }




        if($page == 1)
        {
            $bookTypes  = $bookModel->get_book_types();

        }else{
            $bookTypes   = [];
        }

        return apiData()
            ->set_data('bookTypes',$bookTypes)
            ->set_data('memstate',$memStatus)
            ->set_data('booklist',$entBookInfo)
            ->send(200,'ok');
    }



    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBookList_other(Request $request)
    {
        $friendUserId   = $request->input('friendUserId',0);
        $userId         = $request->input('tokenUserId',0);

        //读取所有书籍
        $bookModel      = new BookModel();
        $entBookInfo    = $bookModel->get_book_list(0,'lhdd');

        foreach ($entBookInfo as $book)
        {
            $book->hasReadPlan = 0;
        }

        define('mem_status_unlogin',3);
        define('mem_status_had_end',1);
        define('mem_status_payed',2);
        define('mem_status_unpay',4);
        $memStatus = mem_status_unlogin;


        $entMemberInfo  = false;
        $memberModel    = new MemberModel();
        if($userId){
            $entMemberInfo = $memberModel->get_member_info_by_id($userId);
        }

        if($entMemberInfo) {
            $memTime    = $entMemberInfo->AddDate;
            $memNumber  = $entMemberInfo->MemNumber;


            //取出该会员所有收藏的书籍
            $collectedBook  = $bookModel->get_member_collected_book($memNumber);
            $colllist       = [];
            foreach($collectedBook as $book){
                array_push($colllist,$book->BookID);
            }


            $readPlanUserMember = $memNumber; //好友的读书改进  如果没有好友 则是自己
            if($friendUserId >0){
                $friendInfo = $memberModel->get_member_info_by_id($friendUserId);
                $readPlanUserMember = $friendInfo->MemNumber;
            }

            //取出已经填写过读书计划的书籍
            $hasWriteReadPlan = DB::table('booksumup')
                ->where('MemNumber',$readPlanUserMember)
                ->distinct()
                ->pluck('BookID')
                ->toArray();
            $hasWriteReadPlan = $hasWriteReadPlan?$hasWriteReadPlan:[];

            //程序调整书籍排列顺序0不显示 1显示
            foreach ($entBookInfo as $book) {
                $bookAddTime    = $book->AddDate;
                $memberAddTime  = $memTime;
                if (strtotime($bookAddTime) > strtotime($memberAddTime)) {
                    $book->IsShow = 0;
                }

                //是否收藏过该书籍 0-否 1-是--MasterID
                $bookId = $book->BookID;
                $book->MasterID     = in_array($bookId, $colllist)?1:0;
                $book->hasReadPlan  = in_array($bookId, $hasWriteReadPlan)?1:0;
            }
        }

        return apiData()
            ->set_data('memstate',$memStatus)
            ->set_data('booklist',$entBookInfo)
            ->send(200,'ok');
    }

    /**
     * 所有书籍
     * @return \Illuminate\Http\JsonResponse
     */
    public function free_books(Request $request)
    {
        //读取所有书籍
        $bookModel      = new BookModel();
        $page           = $request->input('page',0);
        $books    = $bookModel->get_book_list($page,'lhdd',1);

        foreach($books as $book)
        {
            $book->bg_img = env('HOST')."/".$book->bg_img;
            $book->Description  = $book->article;
            $book->ReadNumber   = change_read_number($book->ReadNumber);
        }
        return apiData()
            ->set_data('books',$books)
            ->send(200,'ok');
    }



    /**
     * 发送书籍PPT
     * */
    public function send_book_ppt(Request $request){

        $email  = $request->input('email','');
        $bookId = $request->input('bookId','');

        $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/";
        $res = preg_match($pattern, $email);
        $apiData= new ApiData();

        if(!$res)
        {
            return $apiData->send(400,"请检查您的邮箱是否正确");
        }

        $bookModel  = new BookModel();
        $bookInfo   = $bookModel->get_book_info($bookId);
        $ppts       = $bookModel->get_book_ppt($bookId);

        //Create a new PHPMailer instance
        $mail = new PHPMailer();

        //$file = public_path('uploads/ppt.zip');
        if(empty($bookInfo->ppt)){
           // return $apiData->send(2001,'本书籍暂无PPT文件');
        }
        $pptFile   = asset($bookInfo->ppt);

        $content = view('other/email-ppt',['ppts'=>$ppts,'bookInfo'=>$bookInfo,'pptFile'=>$pptFile]);
        //return $content;
        $ext    = explode('.',$bookInfo->ppt);

        $mail->SMTPDebug = 0;
        $mail->IsSMTP(); // 启用SMTP
        $mail->Port = 465;
        //$mail->Host='smtp.sina.cn'; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->Host='ssl://smtp.qq.com'; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = true; //启用smtp认证

        //$mail->Username = 'zhweixi@sina.cn'; //你的邮箱名
        //$mail->Password = 'zhangweixi123' ; //邮箱密码

       // $mail->Username = '3367067598@qq.com'; //你的邮箱名
       // $mail->Password = 'pqmlpzsxufhadbid' ; //邮箱密码
       // $mail->From = '3367067598@qq.com'; //发件人地址（也就是你的邮箱地址）


        $mail->Username = '2053056069@qq.com'; //你的邮箱名
        $mail->Password = 'fpsnegirmmrgcaea'; //邮箱密码
        $mail->From     = '2053056069@qq.com'; //发件人地址（也就是你的邮箱地址）



        $mail->FromName = "教导读书会"; //发件人姓名
        $mail->AddAddress($email,"尊敬的客户");
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(true); // 是否HTML格式邮件
        $mail->CharSet='utf-8'; //设置邮件编码
        $mail->Subject ="书籍《".$bookInfo->BookTitle."》PPT"; //邮件主题
        //$mail->AddAttachment($file,$bookInfo->BookTitle."PPT.".$ext[1]);
        $mail->Body = $content; //邮件内容
        $mail->AltBody = "活动信息"; //邮件正文不支持HTML的备用显示

        $result = $mail->Send();
        $mobile = $request->input('mobile','');
        $logInfo    = [
            'email'     => $email,
            'book_id'   => $bookId,
            'mobile'    => $mobile,
            'result'    => $mail->ErrorInfo,
            'created_at'=> date_time()
        ];
        DB::table('book_ppt_download_log')->insertGetId($logInfo);

        if($result){
            $memberModel    = new MemberModel();
            $memberInfo     = $memberModel->get_member_info_by_mobile($mobile);
            $memberModel->update_member_info(['UserID'=>$memberInfo->UserID,'email'=>$email]);
            return $apiData->send(200,'PPT发送成功');
        }else{
            return $apiData->send(400,$mail->ErrorInfo);
        }
    }


    /**
     * 国政书吧首页
     * */
    public function gz_index()
    {
        $bookModel  = new BookModel();
        $gzVideos   = $bookModel->get_gz_videos();

        foreach($gzVideos as $video)
        {
            $video->publish_date = str_replace('-','/',$video->publish_date);
        }

        $images     = $bookModel->get_gz_index_images();
        foreach($images as $img)
        {
            $img->link  = env('HOST')."/sharedetail/{$img->content_id}.html";
			$img->type  = $img->type == "article"  ? "web" : $img->type;
            $img->img   = env('HOST')."/".$img->img;
        }

        //获得国政书吧的导航
        $navs = $bookModel->get_book_types(1);
        return $this->apiData
            ->set_data('indexImages',$images)
            ->set_data('navs',$navs)
            ->set_data('videos',$gzVideos)
            ->send(200,'ok');
    }



    /**
     * 获得国政书吧视频列表
     * */
    public function get_gz_videos(Request $request)
    {
        $bookModel  = new BookModel();
        $type       = $request->input('type',0);
        $videos     = $bookModel->get_gz_videos($type);
        return $this->apiData
            ->set_data('data',$videos)
            ->send_old(200,'ok');
    }


    /**
     * 国政书吧视频列表详情
     * */
    public function get_gz_video_detail(Request $request)
    {
        $mobile     = $request->input('mobile');
        $key        = $request->input('key');
        $bookId     = $request->input('bookId');
        $memberInfo = false;
        if($mobile && $key)
        {
            $memberModel    = new MemberModel();
            $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);
        }
        $userId = $memberInfo?$memberInfo->UserID:0;


        $bookModel  = new BookModel();
        $videoInfo  = $bookModel->get_book_info($bookId);
        DB::table('bookinfo')->where('BookID',$bookId)->update(['ReadNumber'=>$videoInfo->ReadNumber+1]);

        $type       = 3;
        $comments   = $this->get_multy_grade_comments($bookId,$type,0,$userId);

        $allVideos  = $bookModel->get_gz_videos();
        $length     = count($allVideos);
        $suiji      =[];
        while(count($suiji) < 2)
        {
            $n      = mt_rand(0,$length-1);
            if(!in_array($n,$suiji))
            {
                array_push($suiji,$n);
            }
        }

        $recommends = [];
        foreach($allVideos as $key=>$video)
        {
            if(in_array($key,$suiji))
            {
                array_push($recommends,$video);
            }
        }
        DB::table('bookinfo')->where('BookID',$bookId)->increment('ReadNumber');
        $videoInfo->shareInfo = [
            'title' => $videoInfo->BookTitle,
            'desc'  => $videoInfo->BookDesc,
            'img'   => $videoInfo->FilePath1,
            'link'  => env('HOST').'/home/shareGuozhengVideo?bookId='.$bookId
        ];
        return $this->apiData
                ->set_data('videoInfo',$videoInfo)
                ->set_data('comments',$comments)
                ->set_data('recommendVideos',$recommends)
                ->send(200,'ok');
    }


    /**
     * 添加评分
     * */
    public function add_score(Request $request)
    {

        $contentId  = $request->input('contentId');
        $contentType= $request->input('contentType');
        $userId     = $request->input('tokenUserId');
        $score      = $request->input('score');

        $paras      = [
            'contentId' => [$contentId,"缺少内容Id"],
            'contentTy' => [$contentType,'缺少内容类型'],
            'score'     => [$score,'缺少分数']
        ];

        $res    = $this->check_params($paras);
        if($res->status == false)
        {
            return apiData()->send(4001,$res->message);
        }
        $scoreModel = new ScoreModel();
        $scoreModel->add_score($userId,$contentId,$contentType,$score);

        $averageInfo= $scoreModel->get_average_score($contentId,$contentType);
        $score      = $averageInfo->score / $averageInfo->total;
        $score      = number_format($score,1);

        $bookModel  = new BookModel();
        $bookModel->where('BookID',$contentId)->update(['score'=>$score]);
        return apiData()->set_data('score',$score)->send(200,'ok');
    }

}